<template>
  <div class="student-matching">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>
            <el-icon><Search /></el-icon>
            学生简历匹配
          </h2>
          <div class="header-actions">
            <el-button type="primary" @click="randomMatch">
              <el-icon><Refresh /></el-icon>
              随机匹配
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索条件 -->
      <el-card class="search-card">
        <el-form :model="searchForm" inline class="search-form">
          <el-form-item label="专业搜索">
            <el-select
              v-model="searchForm.major"
              placeholder="选择专业"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="option in majorLabels"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="技能搜索">
            <el-input
              v-model="searchSkills"
              placeholder="输入技能关键词，用逗号分隔"
              style="width: 300px"
            />
          </el-form-item>
          
          <el-form-item label="GPA范围">
            <el-input-number
              v-model="searchForm.minGPA"
              :min="0"
              :max="4.0"
              :precision="2"
              placeholder="最小值"
              style="width: 100px"
            />
            <span style="margin: 0 10px">-</span>
            <el-input-number
              v-model="searchForm.maxGPA"
              :min="0"
              :max="4.0"
              :precision="2"
              placeholder="最大值"
              style="width: 100px"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="searchStudents" :loading="searching">
              <el-icon><Search /></el-icon>
              搜索学生
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 搜索结果 -->
      <div class="results-section">
        <div class="results-header">
          <h3>匹配结果 ({{ students.length }} 名学生)</h3>
          <div class="views-control">
            <el-radio-group v-model="viewMode" @change="switchViewMode">
              <el-radio-button label="card">卡片视图</el-radio-button>
              <el-radio-button label="list">列表视图</el-radio-button>
            </el-radio-group>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <el-loading-spinner />
          <p>正在搜索匹配的学生...</p>
        </div>

        <!-- 空状态 -->
        <div v-else-if="students.length === 0" class="empty-state">
          <el-empty description="暂无匹配的学生">
            <el-button type="primary" @click="randomMatch">随机匹配</el-button>
          </el-empty>
        </div>

        <!-- 卡片视图 -->
        <div v-else-if="viewMode === 'card'" class="card-grid">
          <el-card
            v-for="student in students"
            :key="student.id"
            class="student-card"
            shadow="hover"
            @click="viewStudentDetail(student)"
          >
            <template #header>
              <div class="student-header">
                <el-avatar :size="50" :src="student.avatar" class="student-avatar">
                  {{ student.real_name?.charAt(0) }}
                </el-avatar>
                <div class="student-info">
                  <div class="student-name">{{ student.real_name }}</div>
                  <div class="student-major">{{ getMajorLabelFn(student.major) }}</div>
                </div>
                <div class="student-score" v-if="student.gpa">
                  <span class="score-label">GPA</span>
                  <span class="score-value">{{ student.gpa }}</span>
                </div>
              </div>
            </template>

            <div class="student-summary">
              <div class="summary-item">
                <span class="item-label">学号：</span>
                <span>{{ student.student_id || '未填写' }}</span>
              </div>
              <div class="summary-item">
                <span class="item-label">年级：</span>
                <span>{{ student.grade || '未填写' }}</span>
              </div>
              <div class="summary-item">
                <span class="item-label">邮箱：</span>
                <span>{{ student.email || '未填写' }}</span>
              </div>
              
              <div v-if<｜tool▁sep｜>student.personal_advantages" class="advantages-preview">
                <strong>个人优势：</strong>
                <p>{{ truncateText(student.personal_advantages, 80) }}</p>
              </div>
            </div>

            <template #footer>
              <div class="card-footer">
                <el-button size="small" @click.stop="viewStudentDetail(student)">
                  <el-icon><View /></el-icon>
                  查看简历
                </el-button>
                <el-button type="primary" size="small" @click.stop="contactStudent(student)">
                  <el-icon><Message /></el-icon>
                  联系学生
                </el-button>
              </div>
            </template>
          </el-card>
        </div>

        <!-- 列表视图 -->
        <el-table v-else :data="students" class="student-table">
          <el-table-column prop="real_name" label="姓名" width="120">
            <template #default="scope">
              <div class="student-cell">
                <el-avatar :size="32" :src="scope.row.avatar">
                  {{ scope.row.real_name?.charAt(0) }}
                </el-avatar>
                <span>{{ scope.row.real_name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="student_id" label="学号" width="120" />
          <el-table-column prop="major" label="专业" width="150">
            <template #default="scope">
              {{ getMajorLabelFn(scope.row.major) }}
            </template>
          </el-table-column>
          <el-table-column prop="grade" label="年级" width="80" />
          <el-table-column prop="gpa" label="GPA" width="80">
            <template #default="scope">
              <el-tag v-if="scope.row.gpa" type="success" size="small">
                {{ scope.row.gpa }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column label="操作" width="160">
            <template #default="scope">
              <el-button size="small" @click="viewStudentDetail(scope.row)">
                <el-icon><View /></el-icon>
                查看简历
              </el-button>
              <el-button type="primary" size="small" @click="contactStudent(scope.row)">
                <el-icon><Message /></el-icon>
                联系
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 学生简历详情对话框 -->
    <el-dialog 
      v-model="detailVisible" 
      :title="`${selectedStudent?.real_name} - 简历详情`"
      width="900px"
      :before-close="handleCloseDetail"
    >
      <ResumePreview v-if="selectedStudent" :resume="selectedStudent" />
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button type="primary" @click="contactCurrentStudent">联系学生</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Search, Refresh, View, Message, 
} from '@element-plus/icons-vue'
import { 
  Resume, 
  majorLabels,
  getRandomStudentsAPI,
  searchStudentsBySkillsAPI,
  searchStudentsByMajorAPI
} from '@/api/resume'
import ResumePreview from './ResumePreview.vue'

const router = useRouter()

// 导入onMounted
import { onMounted } from 'vue'

// 响应式数据
const loading = ref(false)
const searching = ref(false)
const viewMode = ref('card')
const students = ref<Resume[]>([])
const detailVisible = ref(false)
const selectedStudent = ref<Resume | null>(null)

// 搜索表单
const searchForm = ref({
  major: '',
  minGPA: 0,
  maxGPA: 4.0,
})

const searchSkills = ref('')

// 主要标签映射函数
const getMajorLabelFn = (majorProp: string) => {
  if (!majorProp) return '未填写'
  const option = majorLabels.find(opt => opt.value === majorProp)
  return option ? option.label : majorProp
}

// 截断文本
const truncateText = (text: string, maxLength: number) => {
  if (!text) return ''
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
}

// 随机匹配
const randomMatch = async () => {
  try {
    loading.value = true
    const response = await getRandomStudentsAPI(20)
    console.log('随机匹配响应:', response)
    students.value = response.data || []
    ElMessage.success(`找到 ${students.value.length} 名学生`)
  } catch (error) {
    ElMessage.error('随机匹配失败')
    console.error('随机匹配错误:', error)
  } finally {
    loading.value = false
  }
}

// 搜索学生
const searchStudents = async () => {
  try {
    searching.value = true
    
    let response
    if (searchSkills.value.trim()) {
      // 按技能搜索
      const skills = searchSkills.value.split(',').map(s => s.trim()).filter(s => s)
      response = await searchStudentsBySkillsAPI({
        skills,
        limit: 50
      })
    } else if (searchForm.value.major) {
      // 按专业搜索
      response = await searchStudentsByMajorAPI(searchForm.value.major, 50)
    } else {
      // 随机匹配
      response = await getRandomStudentsAPI(20)
    }
    
    students.value = response.data || []
    
    // 按GPA筛选
    if (searchForm.value.minGPA > 0 || searchForm.value.maxGPA < 4.0) {
      students.value = students.value.filter(student => {
        if (!student.gpa) return false
        return student.gpa >= searchForm.value.minGPA && student.gpa <= searchForm.value.maxGPA
      })
    }
    
    ElMessage.success(`找到 ${students.value.length} 名匹配的学生`)
  } catch (error) {
    ElMessage.error('搜索失败')
    console.error(error)
  } finally {
    searching.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    major: '',
    minGPA: 0,
    maxGPA: 4.0,
  }
  searchSkills.value = ''
  students.value = []
  ElMessage.info('搜索条件已重置')
}

// 切换视图模式
const switchViewMode = () => {
  // 视图模式切换的逻辑，如果有特殊处理可以在这里添加
}

// 查看学生详情
const viewStudentDetail = (student: Resume) => {
  selectedStudent.value = student
  detailVisible.value = true
}

// 联系学生
const contactStudent = (student: Resume) => {
  if (!selectedStudent.value) {
    ElMessage.warning('请先选择一名学生')
    return
  }
  
  // 跳转到聊天页面
  router.push({
    path: '/chat',
    query: {
      userId: student.user_id,
      userName: student.real_name,
      topicTitle: ''
    }
  })
}

// 联系当前学生
const contactCurrentStudent = () => {
  if (selectedStudent.value) {
    contactStudent(selectedStudent.value)
  }
}

// 关闭详情对话框
const handleCloseDetail = () => {
  detailVisible.value = false
  selectedStudent.value = null
}

// 页面加载时自动随机匹配
onMounted(() => {
  randomMatch()
})
</script>

<style scoped>
.student-matching {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.results-section {
  margin-top: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.results-header h3 {
  margin: 0;
}

.views-control {
  display: flex;
  gap: 10px;
}

.loading-state {
  text-align: center;
  padding: 40px;
}

.empty-state {
  text-align: center;
  padding: 40px;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.student-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.student-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.student-header {
  display: flex;
  align-items: center;
  gap: 12px;
}

.student-info {
  flex: 1;
}

.student-name {
  font-weight: 600;
  font-size: 16px;
  color: #333;
}

.student-major {
  font-size: 14px;
  color: #666;
  margin-top: 2px;
}

.student-score {
  text-align: right;
}

.score-label {
  display: block;
  font-size: 12px;
  color: #666;
}

.score-value {
  font-size: 18px;
  font-weight: 600;
  color: #409eff;
}

.student-summary {
  font-size: 14px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.item-label {
  font-weight: 500;
  color: #666;
}

.advantages-preview {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #e4e7ed;
}

.advantages-preview strong {
  display: block;
  margin-bottom: 4px;
  font-size: 13px;
}

.advantages-preview p {
  margin: 0;
  font-size: 13px;
  color: #666;
  line-height: 1.4;
}

.card-footer {
  display: flex;
  justify-content: space-between;
}

.student-table {
  margin-top: 20px;
}

.student-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .student-matching {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-form {
    flex-direction: column;
    gap: 12px;
  }
  
  .card-grid {
    grid-template-columns: 1fr;
  }
  
  .results-header {
    flex-direction: column;
    gap: 12px;
  }
}
</style>
